package leetcode.nnumsum;

import java.util.Arrays;


public class Lc16 {

    public int threeSumClosest(int[] nums, int target) {
        int ans = 0;
        int minAbs = Integer.MAX_VALUE;
        Arrays.sort(nums);
        for (int first = 0; first < nums.length - 2; first++) {
            int l = first + 1;
            int r = nums.length - 1;
            while (l < r) {
                int sum = nums[first] + nums[l] + nums[r];
                if (Math.abs(sum - target) < minAbs) {
                    minAbs = Math.abs(sum - target);
                    ans = sum;
                }
                if (sum < target) l++;
                else if (sum > target) r--;
                else return ans;
            }
        }
        return ans;
    }


}
